package com.rrd.hive.udf;

import com.weicai.caesar.CaesarUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

import java.security.NoSuchAlgorithmException;


@Description(
        name = "caesar_md5",
        value = "_FUNC_(str) - md5 encode str or caesar encode str",
        extended = "Example:\n> SELECT _FUNC_('13811360000');\n  BA275B671FF78D0843AF159C23B6EE51\n> SELECT _FUNC_('6jxdXEKdEo/bHVdtUWshLZmfEBahoIMjHUUtRRjvrJM=');\n  BA275B671FF78D0843AF159C23B6EE51"
)
public class CaesarMd5UDF extends UDF {

    public Text evaluate(String str) throws NoSuchAlgorithmException {
        Text text = new Text();
        if (str == null || str.equals("")) {
            return null;
        }
        String s;
        if (CaesarUtil.isEncrypted(str)) {
            s = getMD5(CaesarUtil.decode(str));
        } else {
            s = getMD5(str);
        }
        text.set(s);

        return text;
    }

    /**
     * MD5加密
     *
     * @param str
     * @return
     */
    public static String getMD5(String str) {
        return DigestUtils.md5Hex(str).toUpperCase();
    }

    public static void main(String[] args) throws Exception {
        CaesarMd5UDF udf = new CaesarMd5UDF();
        System.out.println(udf.evaluate(CaesarUtil.encode("13811363008")).toString().equals(DigestUtils.md5Hex("13811363008").toUpperCase()));

    }
}
